package com.yxr.affairs;

import android.app.Application;
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.support.multidex.MultiDex;
import android.widget.RemoteViews;

import com.tencent.bugly.Bugly;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.RxRetrofitApp;
import com.yxr.affairs.api.Constants;
import com.yxr.affairs.api.ServerApi;
import com.yxr.affairs.utils.ConfigUtil;
import com.yxr.affairs.utils.ToastUtil;
import com.yxr.affairs.utils.UserInfo;

public class MyApplication extends Application implements Constants{

    public static String channel_id = null;

    private static MyApplication mApplication;

    public static MyApplication getApplication(){
        return mApplication;
    }

    public static ConfigUtil cfg = null;

    @Override
    public void onCreate() {
        super.onCreate();
        mApplication = this;

     //   Bugly.init(getApplicationContext(), "fae0fc19ac", false);

        if (cfg == null) {
            cfg = ConfigUtil.ins(this);
        }

        MultiDex.install(this);
        RxRetrofitApp.init(this, BuildConfig.DEBUG);
//        RxRetrofitApp.init(this);

        ServerApi.init(mApplication);

        if (channel_id == null) {
            try {
                ApplicationInfo appInfo = this.getPackageManager().getApplicationInfo(getPackageName(),
                        PackageManager.GET_META_DATA);
                channel_id = appInfo.metaData.getString("UMENG_CHANNEL");
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        }

        UMConfigure.init(this, UMConfigure.DEVICE_TYPE_PHONE, null);
        umengPush();

        UMShareAPI.get(this);
        PlatformConfig.setWeixin(WXAppId, WXAppSecret);
        PlatformConfig.setQQZone(QQAPPID, QQAPPKEY);
    }

    public static String device_token;

    private void umengPush(){
        PushAgent mPushAgent = PushAgent.getInstance(this);

        //注册推送服务，每次调用register方法都会回调该接口
        mPushAgent.register(new IUmengRegisterCallback() {

            @Override
            public void onSuccess(String deviceToken) {
                //注册成功会返回device token
                device_token = deviceToken;
                //手动获取device token，可以调用mPushAgent.getRegistrationId()
            }

            @Override
            public void onFailure(String s, String s1) {

            }
        });

        UmengMessageHandler messageHandler = new UmengMessageHandler(){
            @Override
            public void dealWithCustomMessage(Context context, final UMessage msg) {
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        UTrack.getInstance(getApplicationContext()).trackMsgClick(msg);//自定义消息的点击统计
//    					UTrack.getInstance(getApplicationContext()).trackMsgDismissed(msg);//自定义消息的忽略统计
                    }
                });
            }

            @Override
            public Notification getNotification(Context context, UMessage msg) {
                switch (msg.builder_id) {
                    case 1:
                        Notification.Builder builder = new Notification.Builder(context);
                        RemoteViews myNotificationView = new RemoteViews(context.getPackageName(), R.layout.push_notification);
                        myNotificationView.setTextViewText(R.id.notification_title, msg.title);
                        myNotificationView.setTextViewText(R.id.notification_text, msg.text);
                        myNotificationView.setImageViewBitmap(R.id.notification_large_icon, getLargeIcon(context, msg));
                        myNotificationView.setImageViewResource(R.id.notification_small_icon, getSmallIconId(context, msg));
                        builder.setContent(myNotificationView)
                                .setSmallIcon(getSmallIconId(context, msg))
                                .setTicker(msg.ticker)
                                .setAutoCancel(true);

                        return builder.getNotification();
                    default:
                        //默认为0，若填写的builder_id并不存在，也使用默认。
                        return super.getNotification(context, msg);
                }
            }
        };
        mPushAgent.setMessageHandler(messageHandler);

        UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {
            @Override
            public void dealWithCustomAction(Context context, UMessage msg) {
//    			msg                            //消息体
//    			msg.extra
//		    	msg.custom                     //自定义消息的内容
//    			msg.title                      //通知标题
//    			msg.text                       //通知内容
//    			msg.extra.get("type")          //通知内容
                if(!UserInfo.isLogin()){
                    launchApp(context, msg);
                    ToastUtil.toast(context,  "您还未登录");
                    return;
                }

                try {
                    String type = msg.extra.get("type");
                    Intent intent;

                    if("gonggao".equals(type)){
                        launchApp(context, msg);
                        /*String article_id = msg.extra.get("article_id");
                        intent = new Intent(context, MessageDetailActivity.class);
                        intent.putExtra("article_id", article_id);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);*/

                    }else if("huodong".equals(type)){
                        launchApp(context, msg);
                        /*String url = msg.extra.get("url");
                        String title = msg.extra.get("title");
                        intent= new Intent(context, SupportBankActivity.class);
                        intent.putExtra("url", url);
                        intent.putExtra("title", title);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);*/

                    }else if("biaodi".equals(type)){
                        launchApp(context, msg);
                        /*String NID = msg.extra.get("NID");
                        intent= new Intent(context, InvestmentProjectActivity.class);
                        intent.putExtra("NID", NID);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);*/

                    }else if("tiyanjin".equals(type)){
                        launchApp(context, msg);
                        /*intent = new Intent(context, MyExperienceActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);*/

                    }else if ("hongbao".equals(type)) {
                        launchApp(context, msg);
                        /*intent = new Intent(context, HbMainActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);*/

                    }else if ("licai".equals(type)) {
                        intent = new Intent(context, MainActivity.class);
                        intent.putExtra("fragname", "Invest");
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);

                    }else if ("caifu".equals(type)) {
                        intent = new Intent(context, MainActivity.class);
                        intent.putExtra("fragname", "Store");
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);

                    }else if ("coupon_index".equals(type)) {
                        launchApp(context, msg);
                        /*intent = new Intent(context, FavorableCentreActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);*/

                    }else if ("my_coupon".equals(type)) {//我的优惠券
                        launchApp(context, msg);
                        /*intent = new Intent(context, MyTicketActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);*/

                    }else if ("borrow_auto".equals(type)) {//现在智能投资
                        launchApp(context, msg);
                        /*intent = new Intent(context, AutomaticBidActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);*/

                    }
                } catch (Exception e) {
                    //
                }
            }
        };
        mPushAgent.setNotificationClickHandler(notificationClickHandler);

        //多少秒内收到同一个应用的多条通知时，不会重复提醒
        mPushAgent.setMuteDurationSeconds(10);
        mPushAgent.setDisplayNotificationNumber(5);
    }

}
